import RenderTemplate from '@/util/hogan/index.js'
import pagiText from './template.js'
import {hasClass,getData} from '@/util/dom/index.js'
import './index.css'
// user es5 proto link

let Pagination = function(){
	this.param = {
		container : null, // a com element which used to display pagination
		pageNum : 1, // dispaly list in No. pageNum(default = 1) page
		pageRange : 3, // display page ranges
		modifySelectPage : null // a callback function which can change caller page 

	}

}

// render pagination component
/*
 * param  userParam  user select page button and deliver param 
*/
Pagination.prototype.render = function(userParam) {
	
	this.renderParam = Object.assign({}, this.param,userParam)

	// content of pagination
	let pageArray = [],
		startPage = this.renderParam.pageNum - this.renderParam.pageRange > 0 
			? this.renderParam.pageNum - this.renderParam.pageRange : 1 ,
		endPage = this.renderParam.pageNum + this.renderParam.pageRange < this.renderParam.totalPages 
			? this.renderParam.pageNum + this.renderParam.pageRange : this.renderParam.totalPages;
	pageArray.push({
		name : "上一页",
		value : this.renderParam.prePage,
		disabled : !this.renderParam.hasPreviousPage
	})
	for(let i = startPage; i <= endPage;  i++){
		pageArray.push({
			name : i,
			value : i,
			active : (i === this.renderParam.pageNum),
			disabled : false
		})
	}
	pageArray.push({
		name : "下一页",
		value : this.renderParam.nextPage,
		disabled : !this.renderParam.hasNextPage
	})
	let pageNum = this.renderParam.pageNum,totalPages = this.renderParam.totalPages;
	let wrapArray = {pageArray,pageNum,totalPages}
	//console.log(pagiText)
	new RenderTemplate(pagiText,wrapArray).render().then((res) => {
		document.getElementsByClassName(this.renderParam.container)[0].innerHTML = res
		this.bindEvent()
		//let element = do
	})
};

Pagination.prototype.bindEvent = function(){

//	document.getElementsByClassName('pg-item').addEventListener('click',() => {
//		console.log(this)
//	})
	let elementArray = document.getElementsByClassName("pg-item")
	for(let i = 0; i< elementArray.length; i++){
		if(!hasClass(elementArray[i],'active')){
			elementArray[i].addEventListener('click',() => {
				//console.log(getData(elementArray[i],"value",false))
				//console.log(this.renderParam)
				typeof this.renderParam.modifySelectPage === 'function' 
					&& this.renderParam.modifySelectPage(getData(elementArray[i],"value",false)) 
			})
		}
		
	}
	
}
Pagination.prototype.getPaginationHtml = function(){
	this.renderParam
}
export default Pagination
